package fun.diaoer.config.security;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import fun.diaoer.common.StringUtil;
import fun.diaoer.entity.DISysPermission;
import fun.diaoer.service.AuthService;
import fun.diaoer.service.security.DiaoerUserDetail;
import fun.diaoer.service.security.DiaoerUserDetailService;
import lombok.extern.slf4j.Slf4j;

/**
 * 调用userdetailService的类
 * @author xiaodiannao
 *
 */
@Slf4j
@Component
public class DiaoerAuthenticationProvider implements AuthenticationProvider {
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Autowired
	private DiaoerUserDetailService userDetailService;
	
	private static final String ADMIN="ADMIN";

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		
		String username = (String) authentication.getPrincipal(); // 这个获取表单输入中返回的用户名;
		String password = (String) authentication.getCredentials(); // 这个是表单中输入的密码；
        if(StringUtil.isBlank(username)&&StringUtil.isBlank(password)) {
			return null;
		}
		String[] cNames = username.split("\\|\\|~~");
		if(cNames!=null && cNames.length==2 && StringUtil.equalsTrim(cNames[1], ADMIN)) {
			//前端登录
			userDetailService.setAdmin(true);
			username=cNames[0];
		}else {
			userDetailService.setAdmin(false);
		}
		  DiaoerUserDetail ud=userDetailService.loadUserByUsername(username);
	        if(!passwordEncoder.matches(password,ud.getPassword())){
	        	throw new BadCredentialsException("用户名或密码错误！");
	        }
	        UsernamePasswordAuthenticationToken result =new DiaoerUsernamePasswordAuthenticationToken(ud, password, ud.getAuthorities());
	        result.setDetails(authentication.getDetails());
	        return result;
	}
	

	@Override
	public boolean supports(Class<?> authentication) {
		// TODO Auto-generated method stub
		return true;
	}

}
